package com.zhb.blog.service;

import com.zhb.blog.NotFoundException;
import com.zhb.blog.dao.TagRepository;
import com.zhb.blog.model.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.List;


@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagRepository tagRepository;
    @Transactional
    @Override
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }
    @Transactional
    @Override
    public Tag getTag(Long id) {
        return tagRepository.findById(id).orElseThrow(() ->new NotFoundException("没有找到编号为"+id+"的分类"));


    }
    @Transactional
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }

    @Override
    public List<Tag> listTag(String ids) {
        //将一个按照1,2,3方式排列的string按逗号split成一个集合
        List<Long> list = new ArrayList<>();
        if(!StringUtils.isEmptyOrWhitespace(ids)){
            String[] split = ids.split(",");
            for (int i = 0;i<split.length;i++){
                list.add(new Long(split[i]));
            }
        }

        return tagRepository.findAllById(list);
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        //根据blogs.size倒序排序
        Sort sort = Sort.by(Sort.Direction.DESC, "blogs.size");
        PageRequest of = PageRequest.of(0, size, sort);
        return tagRepository.findTop(of);
    }

    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag t = tagRepository.findById(id).orElseThrow(() ->new NotFoundException("没有找到编号为"+id+"的分类"));

        BeanUtils.copyProperties(tag,t);//将tag赋值给t

        return tagRepository.save(t);
    }
    @Transactional
    @Override
    public void deleteTag(Long id) {
        tagRepository.deleteById(id);
    }

    @Transactional
    @Override
    public Tag getTagByName(String name) {
        return tagRepository.findByName(name);
    }
}
